package com.sdleyou.treepro.common.service.impl;

import com.sdleyou.treepro.common.model.dao.LastRequestTimeDO;
import com.sdleyou.treepro.common.model.dao.LoginTimeDO;
import com.sdleyou.treepro.common.model.dao.SignIn;
import com.sdleyou.treepro.common.service.LastRequestTimeManager;
import com.sdleyou.treepro.common.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class LastRequestTimeManagerImpl implements LastRequestTimeManager {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新最后一次访问接口时间
     */
    @Override
    public void update(String userId) {
        Query query = new Query(Criteria.where("user_id").is(userId));
        LastRequestTimeDO request = mongoTemplate.findOne(query, LastRequestTimeDO.class);
        if(request==null){
            request = new LastRequestTimeDO();
            request.setUserId(userId);
            request.setTime(DateUtil.getDateline());
            mongoTemplate.insert(request);
        }else {
            Update update = new Update();
            update.set("time", DateUtil.getDateline());
            mongoTemplate.updateFirst(query, update, LastRequestTimeDO.class);
        }
    }

    /**
     * 获取最后一次访问接口时间
     */
    @Override
    public Long getLastRequestTime(String userId) {
        Query query = new Query(Criteria.where("user_id").is(userId));
        LastRequestTimeDO request = mongoTemplate.findOne(query, LastRequestTimeDO.class);
        if(request!=null) {
            return request.getTime();
        }else {
            return null;
        }
    }

    /**
     * 获取用户登陆时间列表
     */
    @Override
    public List<SignIn> getLoginList(String userId) {
        Query query = new Query(Criteria.where("user_id").is(userId));
        LoginTimeDO loginTimeDO = mongoTemplate.findOne(query, LoginTimeDO.class);
        if(loginTimeDO==null){
            loginTimeDO = new LoginTimeDO();
            loginTimeDO.setUserId(userId);
            loginTimeDO.setSignInList(createSignInList());
            mongoTemplate.insert(loginTimeDO);
            return loginTimeDO.getSignInList();
        }else{
            return loginTimeDO.getSignInList();
        }
    }

    /**
     * 更新用户登陆时间列表
     */
    @Override
    public void setLoginList(String userId) {
        Query query = new Query(Criteria.where("user_id").is(userId));
        LoginTimeDO loginTimeDO = mongoTemplate.findOne(query, LoginTimeDO.class);
        if(loginTimeDO==null){
            loginTimeDO = new LoginTimeDO();
            loginTimeDO.setUserId(userId);
            loginTimeDO.setSignInList(createSignInList());
            mongoTemplate.insert(loginTimeDO);
        }else {
            try {
                List<SignIn> signInList = loginTimeDO.getSignInList();
                SignIn todaySignIn = new SignIn(DateUtil.getFormatTime());
                boolean isSet = false;
                for (SignIn signIn : signInList) {
                    if (todaySignIn.getSignInDay().compareTo(signIn.getSignInDay()) == 0) {
                        isSet = true;
                        break;
                    }
                }
                if(!isSet) {
                    signInList.add(todaySignIn);
                    signInList.sort(new Comparator<SignIn>() {
                        @Override
                        public int compare(SignIn o1, SignIn o2) {
                            return o2.getSignInDay().compareTo(o1.getSignInDay());
                        }
                    });
                    Update update = new Update();
                    update.set("sign_in_list", signInList);
                    mongoTemplate.updateFirst(query, update, LoginTimeDO.class);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建登陆时间列表
     * @return
     */
    private List<SignIn> createSignInList() {
        List<SignIn> signInList;
        signInList = new ArrayList<>();
        try {
            signInList.add(new SignIn(DateUtil.getFormatTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return signInList;
    }

    /**
     * 获取连续签到次数
     * @return
     * @throws ParseException
     */
    @Override
    public int getContinuousSignInDay(String userId) {

        List<SignIn> signInList = getLoginList(userId);

        //continuousDay 连续签到数
        int continuousDay = 1;
        boolean todaySignIn = false;
        // today 当天日期
        Date today = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String todays=sdf.format(today);

        for (int i = 0; i < signInList.size(); i++) {
            SignIn signIn = signInList.get(i);
            int intervalDay = 0;
            try {
                intervalDay = DateUtil.distanceDay(sdf.parse(todays), signIn.getSignInDay());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //当天签到
            if (intervalDay == 0 && i == 0) {
                todaySignIn = true;
            }else if (intervalDay == continuousDay) {
                continuousDay++;
            }else {
                //不连续，终止判断
                break;
            }
        }
        if (!todaySignIn) {
            continuousDay--;
        }
        return continuousDay;
    }
}
